from sqlalchemy.sql import text
from sqlalchemy import func
from flask import Blueprint, render_template, request, g, current_app, jsonify
from decorators import *
from .forms import PatientForm, IdForm, TableForm
from models import Patient
from exts import db

bp = Blueprint('patient', __name__, url_prefix='/patient')

# 表格页
@bp.route('/patient_page')
@login_required
def patient_page():
    return render_template('patient_page.html')

# 添加操作
@bp.route('/add', methods=['POST'])
@login_required_ajax
def add():
    form = PatientForm(request.form)
    if form.validate():
        name = form.name.data
        disease = form.disease.data
        address = form.address.data
        age = form.age.data
        sex = form.sex.data
        operator_id = g.user.id
        patient = Patient(name=name, disease=disease, address=address, age=age, sex=sex, operator_id=operator_id)
        db.session.add(patient)
        db.session.commit()
        return {'success': True}
    else:
        return {'success': False, 'msg': '数据格式有误，请检查后重试'}

# 更新操作
@bp.route('/update', methods=['POST'])
@login_required_ajax
def update():
    p_form = PatientForm(request.form)
    i_form = IdForm(request.form)
    if p_form.validate() and i_form.validate():
        id = i_form.id.data
        # 执行修改
        Patient.query.filter_by(id=id).update({
            'name': p_form.name.data,
            'disease': p_form.disease.data,
            'address': p_form.address.data,
            'age': p_form.age.data,
            'sex': p_form.sex.data,
            'operator_id': g.user.id
        })
        db.session.commit()
        return {'success': True}
    else:
        return {'success': False, 'msg': '数据格式有误，请检查后重试'}

# 删除操作
@bp.route('/delete', methods=['POST'])
@login_required_ajax
def delete():
    form = IdForm(request.form)
    if form.validate():
        id = form.id.data
        Patient.query.filter_by(id=id).delete()
        db.session.commit()
        return {'success': True}
    else:
        return {'success': False, 'msg': '数据格式有误，请检查后重试'}

# 病人的表格数据
@bp.route('/data_page')
@login_required_ajax
def data_page():
    form = TableForm(request.args)
    name = request.args.get('name')
    page = form.page.data
    limit = form.limit.data
    # 条件查询，其中last_time(最近一次标注时间)为null的优先放最前面
    sql = text('''
        SELECT id,name,disease,address,age,sex,image_id, DATE_FORMAT(last_time, '%Y-%m-%d %H:%i:%s') as last_time
        FROM sys_data.patient
        where name like :name
        order by IF(ISNULL(last_time),0,1), last_time
        limit :offset,:size
    ''')
    data_list = db.session.execute(sql, {'name': '%{}%'.format(name), 'offset': (page - 1) * limit, 'size': limit})
    count_num = db.session.query(func.count(Patient.id)).filter(Patient.name.like('%{}%'.format(name))).scalar()
    patient_list = []
    for data in data_list:
        # current_app.logger.info(data)
        patient_list.append({
            'id': data[0],
            'name': data[1],
            'disease': data[2],
            'address': data[3],
            'age': data[4],
            'sex': data[5],
            'image_id': data[6],
            'last_time': data[7]
        })
    #     layui table 的规定格式
    return jsonify({
        "code": 0,
        "msg": "",
        "count": count_num,
        "data": patient_list
    })
